import {login} from '@/services/user/api';
import {
  ArrowLeftOutlined,
  LockOutlined,
  MobileOutlined,
  UserOutlined, WechatOutlined,
} from '@ant-design/icons';
import {
  LoginFormPage,
  ProConfigProvider,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import {history, useIntl, useModel} from '@umijs/max';
import {Alert, Button, Divider, Space, Tabs, message, theme, Row, Col, Input, Form, QRCode} from 'antd';
import React, {CSSProperties} from 'react';
import {useState} from 'react';
import {flushSync} from 'react-dom';
import bg from "@/pages/user/images/bg.png";
//@ts-ignore
import bgVideo from "@/pages/user/images/bg_video.mp4";
import WechatLogin from './components/WechatLogin';
import {sendCode} from "@/pages/user/register/service";

type LoginType = 'phone' | 'email' | 'wechat';

const iconStyles: CSSProperties = {
  color: 'rgba(0, 0, 0, 0.2)',
  fontSize: '18px',
  verticalAlign: 'middle',
  cursor: 'pointer',
};

const LoginMessage: React.FC<{
  content: string;
}> = ({content}) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Page = () => {
  const [loginType, setLoginType] = useState<LoginType>('email');
  const {token} = theme.useToken();
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const {initialState, setInitialState} = useModel('@@initialState');
  const intl = useIntl();
  const [time, setTime] = useState(Date.now())
  const [form] = Form.useForm();

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      const res = await login({...values, identityType: loginType});

      if (res.code === 0) {
        window.localStorage.setItem('token', res.data?.tokenValue)
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        window.location.href = urlParams.get('redirect') || '/';
        return;
      }
      // console.log(msg);
      // 如果失败去设置用户错误信息
      setUserLoginState(res);
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };

  const {code = 0} = userLoginState;

  const PhoneLogin = <>
    {code !== 0 && <LoginMessage content="验证码错误"/>}
    <>
      <ProFormText
        fieldProps={{
          size: 'large',
          prefix: (
            <MobileOutlined
              style={{
                color: token.colorText,
              }}
              className={'prefixIcon'}
            />
          ),
        }}
        name="identifier"
        placeholder={'手机号'}
        rules={[
          {
            required: true,
            message: '请输入手机号！',
          },
          {
            pattern: /^1\d{10}$/,
            message: '手机号格式错误！',
          },
        ]}
      />

      {/* 图形验证码 */}
      <Row gutter={8}>
        <Col span={16}>
          <Form.Item
            name="captcha"
            rules={[
              {
                required: true,
                message: '请输入图形验证码!',
              },
            ]}
          >
            <Input size="large" placeholder="图形验证码"/>
          </Form.Item>
        </Col>
        <Col span={8}>
          <a onClick={() => {
            setTime(Date.now())
          }}>
            <img width={104} height={40} src={`/account-service/api/v1/notify/captcha?time=${time}`}
                 alt={'图形验证码'}/>
          </a>
        </Col>
      </Row>

      <ProFormCaptcha
        fieldProps={{
          size: 'large',
          prefix: (
            <LockOutlined
              style={{
                color: token.colorText,
              }}
              className={'prefixIcon'}
            />
          ),
        }}
        captchaProps={{
          size: 'large',
        }}
        placeholder={'请输入验证码'}
        captchaTextRender={(timing, count) => {
          if (timing) {
            return `${count} ${'获取验证码'}`;
          }
          return '获取验证码';
        }}
        name="code"
        rules={[
          {
            required: true,
            message: '请输入验证码！',
          },
        ]}
        onGetCaptcha={async () => {
          const values = await form.validateFields(['captcha', 'identifier'])
          if (!values.captcha) {
            return
          }
          const res = await sendCode({captcha: values.captcha, to: values.identifier, type: 'USER_LOGIN'})
          if (res.code === 0) {
            message.success('发送验证码成功！');
          }
        }}
      />
    </>
  </>

  const EmailLogin = <>
    {code !== 0 && (
      <LoginMessage
        content={intl.formatMessage({
          id: 'pages.login.accountLogin.errorMessage',
          defaultMessage: '账户或密码错误(admin/ant.design)',
        })}
      />
    )}
    <ProFormText
      name="identifier"
      fieldProps={{
        size: 'large',
        prefix: (
          <UserOutlined
            style={{
              color: token.colorText,
            }}
            className={'prefixIcon'}
          />
        ),
      }}
      placeholder={'请输入用户名'}
      rules={[
        {
          required: true,
          message: '请输入用户名!',
        },
      ]}
    />
    <ProFormText.Password
      name="credential"
      fieldProps={{
        size: 'large',
        prefix: (
          <LockOutlined
            style={{
              color: token.colorText,
            }}
            className={'prefixIcon'}
          />
        ),
      }}
      placeholder={'请输入密码'}
      rules={[
        {
          required: true,
          message: '请输入密码！',
        },
      ]}
    />
  </>

  const GeneralLogin = <>
    <Tabs
      centered
      activeKey={loginType}
      onChange={(activeKey) => {
        setLoginType(activeKey as LoginType)
        setUserLoginState({})
      }}
    >
      <Tabs.TabPane key={'email'} tab={'账号密码登录'}/>
      <Tabs.TabPane key={'phone'} tab={'手机号登录'}/>
    </Tabs>
    {loginType === 'email' && EmailLogin}
    {loginType === 'phone' && PhoneLogin}
    <div
      style={{
        marginBlockEnd: 24,
      }}
    >
      <ProFormCheckbox noStyle name="autoLogin">
        自动登录
      </ProFormCheckbox>
      <a
        style={{
          float: 'right',
        }}
      >
        忘记密码
      </a>
    </div>
  </>

  return (
    <div
      style={{
        backgroundColor: 'white',
        height: '100vh',
      }}
    >
      <LoginFormPage
        backgroundImageUrl={bg}
        logo="/logo.svg"
        form={form}
        backgroundVideoUrl={bgVideo}
        title="烟蓝云测"
        containerStyle={{
          backgroundColor: 'rgba(0, 0, 0,0.65)',
          backdropFilter: 'blur(4px)',
        }}
        subTitle="一键加速测试，质效双赢"
        activityConfig={{
          style: {
            boxShadow: '0px 0px 8px rgba(0, 0, 0, 0.2)',
            color: token.colorTextHeading,
            borderRadius: 8,
            backgroundColor: 'rgba(255,255,255,0.25)',
            backdropFilter: 'blur(4px)',
          },
          title: '简化测试繁琐，加速产品飞跃。',
          subTitle: '加入烟蓝自动化测试平台体验日，探索统一接口、UI及压力测试新境界。无论公有云还是私有云环境，可视化编排让测试流程自如流转。自动生成报告，精准把控软件质量，缩短交付周期。让我们携手，让测试更智能，更高效！',
          action: (
            <Button
              size="large"
              style={{
                borderRadius: 20,
                background: 'rgba(0,0,0,.1)',
                color: '#fff',
                width: 120,
              }}
            >
              去看看
            </Button>
          ),
        }}
        initialValues={{
          autoLogin: true,
          // identifier: '295755973@qq.com',
          // credential: 123456
        }}
        onFinish={async (values) => {
          await handleSubmit(values as API.LoginParams);
        }}
        submitter={loginType !== 'wechat' ? undefined : {render: () => <></>}}
        actions={
          loginType !== 'wechat' ? <div
            style={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              flexDirection: 'column',
            }}
          >
            <Button type='link' block
                    onClick={() => {
                      history.push("/user/register")
                    }}
                    style={{paddingBottom: 0, height: 'auto', marginTop: 5}}>去注册</Button>
            <Divider plain>
                            <span
                              style={{
                                color: token.colorTextPlaceholder,
                                fontWeight: 'normal',
                                fontSize: 14,
                              }}
                            >
                                其他登录方式
                            </span>
            </Divider>
            <Space align="center" size={24}>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  flexDirection: 'column',
                  height: 40,
                  width: 40,
                  border: '1px solid ' + token.colorPrimaryBorder,
                  borderRadius: '50%',
                }}
                onClick={() => {
                  setLoginType("wechat")
                }}
              >
                <WechatOutlined style={{...iconStyles, color: '#51C332'}}/>
              </div>
            </Space>
          </div> : <></>
        }
      >
        {loginType !== 'wechat' && GeneralLogin}

        {loginType === 'wechat' && <WechatLogin
          onBack={() => {
            setLoginType('email')
          }}/>}

      </LoginFormPage>
    </div>
  );
};

export default () => {
  return (
    <ProConfigProvider dark>
      <Page/>
    </ProConfigProvider>
  );
};
